<?php

// 雪里开简易预约制访客管理系统 V1.0（2025.05.20）
// 演示地址: http://fangke.chalide.cn
// 更新关注: /weivote/yuyuefangke
// 文件路径: stu/vist.php
// 文件大小: 19234 字节
// 最后修改时间: 2025-05-20 22:25:16
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
/**
 * 学生访客申请
 * 功能反馈:15058593138@qq.com
 */

// 获取分页参数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page);
$pageSize = 10;

// 获取搜索参数
$search_field = get_param('search_field', 'vname');
$search_value = get_param('search_value', '');

// 获取当前学生ID
$stuid = $_SESSION['user_id'];

// 获取系统设置
$db = new MySQLDB();
$settings = [];
$res = $db->getAll("SELECT * FROM `site`");
if ($res) {
    foreach ($res as $item) {
        $settings[$item['skey']] = $item['sval'];
    }
}

// 处理AJAX请求
if (isset($_GET['act'])) {
    switch ($_GET['act']) {
        case 'add':
            // 检查是否允许访客申请
            if (isset($settings['allow_visit']) && $settings['allow_visit'] != '1') {
                json_error('系统当前已关闭访客申请功能');
            }
            
            // 检查访问时间是否在允许范围内
            $visit_start_time = isset($settings['visit_start_time']) ? $settings['visit_start_time'] : '08:00';
            $visit_end_time = isset($settings['visit_end_time']) ? $settings['visit_end_time'] : '22:00';
            $current_time = date('H:i');
            
            if ($current_time < $visit_start_time || $current_time > $visit_end_time) {
                json_error("当前时间不在允许申请的时间范围内（{$visit_start_time}~{$visit_end_time}）");
            }
            
            // 获取表单参数
            $room = post_param('room');
            $reason = post_param('reason');
            $vname = post_param('vname');
            $vtel = post_param('vtel');
            $vdate = post_param('vdate');
            
            // 简单验证
            if (!$room || !$reason || !$vname || !$vtel || !$vdate) {
                json_error('所有字段都不能为空');
            }
            
            // 验证到访日期
            $current_date = date('Y-m-d');
            if ($vdate < $current_date) {
                json_error('到访日期不能早于今天');
            }
            
            // 生成访客码
            $vcode = generate_visit_code();
            
            // 新增数据
            $data = [
                'stuid' => $stuid,
                'room' => $room,
                'reason' => $reason,
                'vname' => $vname,
                'vtel' => $vtel,
                'vdate' => $vdate,
                'vcode' => $vcode
            ];
            
            $result = $db->insert('vist', $data);
            
            if ($result) {
                json_success('申请成功', ['vcode' => $vcode]);
            } else {
                json_error('申请失败：' . $db->getError());
            }
            break;
            
        case 'delete':
            // 获取参数
            $id = post_param('id');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 检查是否为自己的记录
            $row = $db->getOne("SELECT * FROM `vist` WHERE `id` = '$id' AND `stuid` = '$stuid'");
            if (!$row) {
                json_error('无权操作此记录');
            }
            
            // 检查是否已核销
            if ($row['htime']) {
                json_error('已核销的记录不能删除');
            }
            
            // 删除数据
            $result = $db->delete('vist', "id = '$id'");
            
            if ($result) {
                json_success('删除成功');
            } else {
                json_error('删除失败：' . $db->getError());
            }
            break;
            
        case 'detail':
            // 获取参数
            $id = post_param('id');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 检查是否为自己的记录
            $row = $db->getOne("SELECT * FROM `vist` WHERE `id` = '$id' AND `stuid` = '$stuid'");
            if (!$row) {
                json_error('无权查看此记录');
            }
            
            json_success('获取成功', $row);
            break;
    }
    exit;
}

// 构建查询条件
$where = "stuid = '$stuid'";
if ($search_value) {
    $search_value = $db->escape($search_value);
    
    switch ($search_field) {
        case 'vname':
            $where .= " AND vname LIKE '%$search_value%'";
            break;
        case 'vtel':
            $where .= " AND vtel LIKE '%$search_value%'";
            break;
        case 'room':
            $where .= " AND room LIKE '%$search_value%'";
            break;
        case 'vcode':
            $where .= " AND vcode LIKE '%$search_value%'";
            break;
    }
}

// 获取分页数据
$result = $db->getPageList('vist', $where, 'id DESC', $page, $pageSize);

$list = $result['list'];
$total = $result['total'];
$totalPage = $result['totalPage'];
// 加载页头
require_once './inc/head.php';
?>

<div class="container">
    <?php if (isset($settings['allow_visit']) && $settings['allow_visit'] != '1'): ?>
    <div class="alert" style="background-color: #f8d7da; color: #721c24; padding: 10px; margin-bottom: 15px; border-radius: 4px;">
        系统当前已关闭访客申请功能
    </div>
    <?php else: ?>
    <div class="alert" style="background-color: #d4edda; color: #155724; padding: 10px; margin-bottom: 15px; border-radius: 4px;">
        访客申请开放时间：<?php echo isset($settings['visit_start_time']) ? $settings['visit_start_time'] : '08:00'; ?>~<?php echo isset($settings['visit_end_time']) ? $settings['visit_end_time'] : '22:00'; ?>
    </div>
    <?php endif; ?>
    
    <div class="search-bar">
        <div class="row" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <div class="col-left">
                <h2 style="margin: 0;">我的访客</h2>
            </div>
            <div class="col-right">
                <button type="button" class="btn btn-primary" onclick="showAddForm()">申请访客</button>
            </div>
        </div>
        
        <form action="" method="get" class="search-form" style="display: flex; margin-bottom: 15px;">
            <input type="hidden" name="do" value="vist">
            <select name="search_field" class="search-select">
                <option value="vname" <?php echo $search_field == 'vname' ? 'selected' : ''; ?>>访客姓名</option>
                <option value="vtel" <?php echo $search_field == 'vtel' ? 'selected' : ''; ?>>访客电话</option>
                <option value="room" <?php echo $search_field == 'room' ? 'selected' : ''; ?>>宿舍号</option>
                <option value="vcode" <?php echo $search_field == 'vcode' ? 'selected' : ''; ?>>访客码</option>
            </select>
            <input type="text" name="search_value" class="search-input" placeholder="请输入搜索内容" value="<?php echo htmlspecialchars($search_value); ?>">
            <button type="submit" class="search-btn">查询</button>
        </form>
    </div>
    
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>访客姓名</th>
                    <th>访客电话</th>
                    <th>宿舍号</th>
                    <th>到访日期</th>
                    <th>访客码</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($list)): ?>
                <?php foreach ($list as $item): ?>
                <tr>
                    <td><?php echo $item['id']; ?></td>
                    <td><?php echo htmlspecialchars($item['vname']); ?></td>
                    <td><?php echo htmlspecialchars($item['vtel']); ?></td>
                    <td><?php echo htmlspecialchars($item['room']); ?></td>
                    <td><?php echo format_date($item['vdate']); ?></td>
                    <td>
                        <span style="font-weight: bold;"><?php echo htmlspecialchars($item['vcode']); ?></span>
                    </td>
                    <td>
                        <?php if ($item['htime']): ?>
                        <span style="color: green;">已核销</span><br>
                        <small><?php echo format_date($item['htime'], 'Y-m-d H:i'); ?></small>
                        <?php else: ?>
                        <span style="color: orange;">未核销</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <button type="button" class="btn btn-default btn-sm" onclick="showDetail(<?php echo $item['id']; ?>)">详情</button>
                        <?php if (!$item['htime']): ?>
                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteRecord(<?php echo $item['id']; ?>, function() { window.location.reload(); })">删除</button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php else: ?>
                <tr>
                    <td colspan="8" align="center">暂无数据</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > 0): ?>
    <div class="table-footer">
        <div class="table-info">共 <?php echo $total; ?> 条记录，第 <?php echo $page; ?>/<?php echo $totalPage; ?> 页</div>
        <?php echo paginate($page, $totalPage, '?do=vist&search_field=' . urlencode($search_field) . '&search_value=' . urlencode($search_value)); ?>
    </div>
    <?php endif; ?>
</div>

<script>
// 显示添加表单
function showAddForm() {
    // 检查是否允许访客申请
    <?php if (isset($settings['allow_visit']) && $settings['allow_visit'] != '1'): ?>
    showToast('系统当前已关闭访客申请功能', 'error');
    return;
    <?php endif; ?>
    
    // 检查访问时间是否在允许范围内
    <?php 
    $visit_start_time = isset($settings['visit_start_time']) ? $settings['visit_start_time'] : '08:00';
    $visit_end_time = isset($settings['visit_end_time']) ? $settings['visit_end_time'] : '22:00';
    $current_time = date('H:i');
    
    if ($current_time < $visit_start_time || $current_time > $visit_end_time): 
    ?>
    showToast('当前时间不在允许申请的时间范围内（<?php echo $visit_start_time; ?>~<?php echo $visit_end_time; ?>）', 'error');
    return;
    <?php endif; ?>
    
    // 设置最小日期为今天
    const today = new Date().toISOString().split('T')[0];
    
    let content = `
    <form id="add-form">
        <div class="form-group">
            <label class="form-label">目标宿舍号</label>
            <input type="text" name="room" class="form-control" required data-name="目标宿舍号">
        </div>
        <div class="form-group">
            <label class="form-label">到访事由</label>
            <textarea name="reason" class="form-control" rows="3" required data-name="到访事由"></textarea>
        </div>
        <div class="form-group">
            <label class="form-label">访客姓名</label>
            <input type="text" name="vname" class="form-control" required data-name="访客姓名">
        </div>
        <div class="form-group">
            <label class="form-label">访客电话</label>
            <input type="text" name="vtel" class="form-control" required data-name="访客电话">
        </div>
        <div class="form-group">
            <label class="form-label">到访日期</label>
            <input type="date" name="vdate" class="form-control" min="${today}" required data-name="到访日期">
        </div>
    </form>
    `;
    
    showMask(content, '申请访客', [
        {
            text: '取消',
            class: 'mask-button-default',
            click: closeMask
        },
        {
            text: '提交申请',
            class: 'mask-button-primary',
            click: function() {
                if (!validateForm('add-form')) return;
                
                ajaxRequest('?do=vist&act=add', getFormData('add-form'), function(res) {
                    if (res.code === 0) {
                        showToast(res.msg, 'success');
                        
                        // 显示访客码
                        let codeContent = `
                        <div style="text-align: center;">
                            <p>请将以下访客码提供给您的访客：</p>
                            <div class="visit-code">${res.data.vcode}</div>
                            <p style="margin-top: 15px; color: #666;">访客需向门卡管理员出示此访客码</p>
                        </div>
                        `;
                        
                        closeMask();
                        showMask(codeContent, '申请成功', [
                            {
                                text: '确定',
                                class: 'mask-button-primary',
                                click: function() {
                                    closeMask();
                                    window.location.reload();
                                }
                            }
                        ]);
                    } else {
                        showToast(res.msg, 'error');
                    }
                });
            }
        }
    ]);
}

// 显示详情
function showDetail(id) {
    ajaxRequest('?do=vist&act=detail', {id: id}, function(res) {
        if (res.code === 0) {
            const data = res.data;
            
            let content = `
            <div class="detail-section">
                <h3 class="detail-title">访客信息</h3>
                <div class="detail-item">
                    <div class="detail-label">姓名:</div>
                    <div class="detail-value">${data.vname}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">电话:</div>
                    <div class="detail-value">${data.vtel}</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">访问信息</h3>
                <div class="detail-item">
                    <div class="detail-label">目标宿舍:</div>
                    <div class="detail-value">${data.room}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">到访日期:</div>
                    <div class="detail-value">${formatDate(data.vdate)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">到访事由:</div>
                    <div class="detail-value">${data.reason}</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">访客码</h3>
                <div class="visit-code">${data.vcode}</div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">核销信息</h3>
                ${data.htime ? `
                <div class="detail-item">
                    <div class="detail-label">核销状态:</div>
                    <div class="detail-value"><span style="color: green;">已核销</span></div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">核销时间:</div>
                    <div class="detail-value">${formatDateTime(data.htime)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">核销账号:</div>
                    <div class="detail-value">${data.huser || '-'}</div>
                </div>
                ` : `
                <div class="detail-item">
                    <div class="detail-label">核销状态:</div>
                    <div class="detail-value"><span style="color: orange;">未核销</span></div>
                </div>
                `}
            </div>
            `;
            
            const buttons = [];
            buttons.push({
                text: '关闭',
                class: 'mask-button-default',
                click: closeMask
            });
            
            // 如果未核销，显示删除按钮
            if (!data.htime) {
                buttons.push({
                    text: '删除',
                    class: 'mask-button-danger',
                    click: function() {
                        closeMask();
                        deleteRecord(id, function() {
                            window.location.reload();
                        });
                    }
                });
            }
            
            showMask(content, '访客详情', buttons);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

// 删除记录
function deleteRecord(id, callback) {
    if (!id) return;
    
    confirmDialog('确定要删除此记录吗？删除后不可恢复！', function() {
        ajaxRequest('?do=vist&act=delete', {
            id: id
        }, function(res) {
            if (res.code === 0) {
                showToast(res.msg, 'success');
                if (callback) callback();
            } else {
                showToast(res.msg, 'error');
            }
        });
    });
}

// 格式化日期
function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0');
}

// 格式化日期时间
function formatDateTime(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0') + ' ' +
           String(date.getHours()).padStart(2, '0') + ':' +
           String(date.getMinutes()).padStart(2, '0') + ':' +
           String(date.getSeconds()).padStart(2, '0');
}
</script>

<style>
.detail-section {
    margin-bottom: 20px;
}
.detail-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #eee;
}
.detail-item {
    display: flex;
    margin-bottom: 8px;
}
.detail-label {
    width: 80px;
    font-weight: bold;
}
.detail-value {
    flex: 1;
}
.table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    padding: 10px 0;
}
.table-info {
    margin-bottom: 10px;
}
.visit-code {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
    letter-spacing: 2px;
}
</style>
